package com.financing.platform.task;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.platform.dao.IMessageMailDao;
import com.financing.platform.dto.MessageMailDTO;
import com.financing.platform.service.IProductSupplierService;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.StringUtil;

@Component(value="outProductSendEmailJob" )
public class OutProductSendEmailJob {

	Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private IMessageMailDao messageMailDaoImpl;
	
	@Value("#{settings['outProductEmail']}")
	private String outProductEmail;
	
	@Autowired
	private IProductSupplierService productSupplierService;
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
//	@Scheduled(cron = "0 0 17 * * ?") 
	public void outProductSendEmail(){
		try{
			List<Map<String, Object>> queryProductSupplierInfoEmail = productSupplierService.queryProductSupplierInfoEmail();
			for (int i = 0; i < queryProductSupplierInfoEmail.size(); i++) {
				StringBuffer mailContent=new StringBuffer("<html><head><meta charset=\"UTF-8\"></head><body>");
				Map<String, Object> map = queryProductSupplierInfoEmail.get(i);
				String id=map.get("id")==null?"0":String.valueOf(map.get("id"));
				List<Map<String, Object>> detail = productSupplierService.queryProductSupplierEmailById(id);
				StringBuffer sb=new StringBuffer("<br>今天跟进进度的产品：<br><table border=\"2\"><td>产品时间</td><td>产品名称</td><td>维护进度</td><td>上一个维护进度</td></tr>");
				StringBuffer sb2=new StringBuffer("<br>今天未跟进产品的产品：<br><table border=\"2\"><tr><td>产品名称</td><td>上一次维护进度时间</td><td>上一次维护进度的进度</td><td>第三方跟进人电话</td></tr>");
				for(Map<String, Object> tmp : detail){
					String updateScheduleDate=tmp.get("updateScheduleDate")==null?"":String.valueOf(tmp.get("updateScheduleDate"));
					boolean flag=false;
					try {
						flag=!StringUtils.isBlank(updateScheduleDate)&&StringUtil.str2Date(updateScheduleDate).after(DateUtil.getDateStarting(new Date()));
					} catch (Exception e) {
						log.error("updateScheduleDate format error",e);
					}
					if(flag){
						sb.append("<td>").append(tmp.get("updateScheduleDate")==null?"--":tmp.get("updateScheduleDate"))
						.append("</td><td>")
						.append(tmp.get("productName"))
						.append("</td><td>")
						.append(tmp.get("pRecruitmentSummary"))
						.append("</td><td>")
						.append(tmp.get("oldPrecruitmentsummary"))
						.append("</td></tr>");
					}else{
						sb2.append("<td>").append(tmp.get("productName"))
						.append("</td><td>")
						.append(tmp.get("updateScheduleDate"))
						.append("</td><td>")
						.append(tmp.get("oldPrecruitmentsummary")==null?tmp.get("pRecruitmentSummary"):tmp.get("oldPrecruitmentsummary"))
						.append("</td><td>")
						.append(tmp.get("accessMobile"))
						.append("</td></tr>");
					}
				}
				sb.append("</table>");
				sb2.append("</table>");
				mailContent.append(sb).append(sb2).append("</body></html>");
				Map<String,String>  param = new HashMap<String,String>();
				param.put(Dict.mail_content, mailContent.toString());
				param.put(Dict.mail_subject, "产品经理-产品进度更新");
				SendOutProductMail(param, String.valueOf(map.get("accessEmail")));
			}
		}catch(Exception e){
			log.error("outProductSendEmail send Mail error ",e);
		}
	}
	
//	@Scheduled(cron = "0 0 17 * * ?") 
	public void outProductSendEmailAll(){
		try{
			List<Map<String, Object>> queryProductSupplierInfoEmail = productSupplierService.queryProductSupplierInfoEmail();
			StringBuffer all=new StringBuffer("<html><head><meta charset=\"UTF-8\"></head><body>");
			for (int i = 0; i < queryProductSupplierInfoEmail.size(); i++) {
				StringBuffer mailContent=new StringBuffer("");
				Map<String, Object> map = queryProductSupplierInfoEmail.get(i);
				String id=map.get("id")==null?"":String.valueOf(map.get("id"));
				List<Map<String, Object>> detail = productSupplierService.queryProductSupplierEmailById(id);
				StringBuffer sb=new StringBuffer("<br>已更新产品的信息包括：<br><table border=\"2\"><td>产品时间</td><td>产品名称</td><td>维护进度</td><td>上一个维护进度</td></tr>");
				StringBuffer sb2=new StringBuffer("<br>未更新产品信息包括：<br><table border=\"2\"><tr><td>产品时间</td><td>产品名称</td><td>维护进度</td><td>产品部维护人名字</td></tr>");
				for(Map<String, Object> tmp : detail){
					String updateScheduleDate=tmp.get("updateScheduleDate")==null?"":String.valueOf(tmp.get("updateScheduleDate"));
					boolean flag=false;
					try {
						flag=!StringUtils.isBlank(updateScheduleDate)&&StringUtil.str2Date(updateScheduleDate).after(DateUtil.getDateStarting(new Date()));
					} catch (Exception e) {
						log.error("updateScheduleDate format error",e);
					}
					if(flag){
						sb.append("<td>").append(tmp.get("updateScheduleDate")==null?"--":tmp.get("updateScheduleDate"))
						.append("</td><td>")
						.append(tmp.get("productName"))
						.append("</td><td>")
						.append(tmp.get("pRecruitmentSummary"))
						.append("</td><td>")
						.append(tmp.get("oldPrecruitmentsummary"))
						.append("</td></tr>");
					}else{
						sb2.append("<td>").append(tmp.get("updateScheduleDate")==null?"--":tmp.get("updateScheduleDate"))
						.append("</td><td>")
						.append(tmp.get("productName"))
						.append("</td><td>")
						.append(tmp.get("pRecruitmentSummary")==null?tmp.get("oldPrecruitmentsummary"):tmp.get("pRecruitmentSummary"))
						.append("</td><td>")
						.append(map.get("accessName"))
						.append("</td></tr>");
					}
				}
				sb.append("</table>");
				sb2.append("</table>");
				mailContent.append(sb).append(sb2);
				all.append("<br/>").append(map.get("accessName")).append(mailContent);
			}
			all.append("</body></html>");
			Map<String,String>  param = new HashMap<String,String>();
			param.put(Dict.mail_content, all.toString());
			param.put(Dict.mail_subject, "总产品负责人---产品进度更新");
			SendOutProductMail(param,outProductEmail);
		}catch(Exception e){
			log.error("outProductSendEmail send Mail error ",e);
		}
	}
	
	/**
	 * 
	 * @Title: SendOutProductMail
	 * @Description: 发送外部产品负责人邮件 
	 * @param @param param
	 * @param @param emailAddress
	 * @param @throws SQLException   
	 * @return void   
	 * @throws
	 */
	private void SendOutProductMail(Map<String,String> param,String emailAddress) throws SQLException{
		if(!param.isEmpty() && param.size() >0){
			MessageMailDTO messageMailDTO = new MessageMailDTO();
			messageMailDTO.setFpMailContent((String)param.get(Dict.mail_content));
			messageMailDTO.setFpMailTitle((String)param.get(Dict.mail_subject));
			messageMailDTO.setFpMailType(Dict.out_product_email);
			messageMailDTO.setFpMailSendType(Dict.message_type_now);
			messageMailDTO.setFpMailSendTimes(new Integer(0));
			messageMailDTO.setStatus(Dict.status_normal);
			messageMailDTO.setFpMailSendStatus(Dict.message_status_not_send);
			messageMailDTO.setCreateBy("system");
			messageMailDTO.setUpdateBy("system");
			messageMailDTO.setCreateDate(new Date());
			messageMailDTO.setUpdateDate(new Date());
			String[] mailAddr = StringUtil.preEmailAddr(emailAddress);
			if(mailAddr!=null){
				for(String addr : mailAddr){
					messageMailDTO.setFpMailTo(addr);
					messageMailDaoImpl.addMessageMail(messageMailDTO);
				}
			}
		}
	}
}
